创建 Library
howcode 2022-07-19 0 webpack
# 新建一个 src 目录的 index.js 文件
export const add = (x, y) => {
return x + y;
};
1
2
3
2
3
# 在 webpac.config.js 里面加入以下配置
const path = require(path)
module.exports = {
mode:'production',
entry: './src/index.js',
output: {
path: path.resolve(__dirname. 'dist'),
filename: 'mylib.js',
// 防止文件被 tree shaking
library: 'mylib'
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
3.使用方式:在 indem.html 里面加入以下代码
<script src='../dist/mylib.js'></script>
<script>
console.log(mylib.add(4,5)) //打印结果为9
</script>
1
2
3
4
2
3
4
mylib 是绑定到 window 对象下
# 详细配置
Library 打包类型:window、commonjs、module、umd,默认打包格式为 window
- window
const path = require(path)
module.exports = {
mode:'production',
entry: './src/index.js',
output: {
path: path.resolve(__dirname. 'dist'),
filename: 'mylib.js',
library: {
name:'mylib',
type:"window"
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
- commonjs
const path = require(path)
module.exports = {
mode:'production',
entry: './src/index.js',
output: {
path: path.resolve(__dirname. 'dist'),
filename: 'mylib.js',
library: {
name:'mylib',
type:"commonjs"
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
使用:
const {mylib} = require(../dist/mylib)
console.log(mylib.add(4,5)) //打印结果为9
1
2
3
2
3
- module
const path = require(path)
module.exports = {
mode:'production',
entry: './src/index.js',
experiments:{
outputModule:true
},
output: {
path: path.resolve(__dirname. 'dist'),
filename: 'mylib.js',
library: {
type:"module"
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
使用:
<script type="module">
import {add} from '../dist/mylib.js' console.log(add(4,5)) //打印结果为9
</script>
1
2
3
2
3
- umd
const path = require(path)
module.exports = {
mode:'production',
entry: './src/index.js',
output: {
path: path.resolve(__dirname. 'dist'),
filename: 'mylib.js',
library: {
name:'mylib',
type:"umd"
},
globalObject:'globalThis'
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
使用
<script src='../dist/mylib.js'></script>
<script>
console.log(mylib.add(4,5)) //打印结果为9
</script>
1
2
3
4
2
3
4
const {add} = require(../dist/mylib)
console.log(add(4,5)) //打印结果为9
1
2
3
2
3
视频教程:https://www.bilibili.com/video/BV1YU4y1g745?p=83
评论
- 表情
——暂无评论——